package binderipcservicemanager

import android.os.Bundle
import android.os.IBinder
import android.os.Parcel

class BCAdvancedServiceManagerProxy(binder: IBinder) : IBCAdvancedServiceManager {

    private val mRemote = binder

    override fun addService(name: String?, binder: IBinder?) {
        val data = Parcel.obtain()
        val reply = Parcel.obtain()
        try {
            data.writeInterfaceToken(IBCAdvancedServiceManager.descriptor)

            data.writeString(name)

            val bundle = Bundle()
            bundle.putBinder(name, binder)
            data.writeBundle(bundle)

            data.writeNoException()

            mRemote.transact(IBCAdvancedServiceManager.TRANSACTION_ADD_SERVICE, data, reply, 0)
        } finally {
            reply.recycle()
            data.recycle()
        }
    }

    override fun getService(name: String?): IBinder? {
        val data = Parcel.obtain()
        val reply = Parcel.obtain()
        try {
            data.writeInterfaceToken(IBCAdvancedServiceManager.descriptor)

            data.writeString(name)
            data.writeNoException()
            mRemote.transact(IBCAdvancedServiceManager.TRANSACTION_GET_SERVICE, data, reply, 0)

            reply.readException()
            val bundle = reply.readBundle(javaClass.classLoader)
            return bundle?.getBinder(name)
        } finally {
            reply.recycle()
            data.recycle()
        }
    }

    override fun removeService(name: String?) {
        val data = Parcel.obtain()
        val reply = Parcel.obtain()
        try {
            data.writeInterfaceToken(IBCAdvancedServiceManager.descriptor)
            data.writeString(name)
            data.writeNoException()
            mRemote.transact(IBCAdvancedServiceManager.TRANSACTION_REMOVE_SERVICE, data, reply, 0)
        } finally {
            reply.recycle()
            data.recycle()
        }
    }

    override fun asBinder(): IBinder {
        return mRemote
    }


}